package com.etime.shycourse.controller.wx.kf;


import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import cn.binarywang.wx.miniapp.util.xml.XStreamTransformer;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etime.shycourse.controller.wx.rss.WXRSSService;
import io.swagger.annotations.Api;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTransferKefuMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 与客服功能相关的controller接口
 * （废弃）
 */
//@Api(tags = "微信-客服相关数据接口")
//@RestController
//@RequestMapping("/wx/kf")
public class WXKFController {

//    @Autowired
    private WXRSSService wxrssService;

    /**
     *
     * @param request
     * @param response
     * @return
     */
    //@RequestMapping(value = {"/getProcessRequest"}, method = {RequestMethod.GET, RequestMethod.POST})
    public Object getProcessRequest123(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        System.out.println("方法是-------" + isGet);
        PrintWriter out = null;
        out = response.getWriter();
        if (isGet) {//首次验证token
            // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            try {
               // out = response.getWriter();
                // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
                if (checkSignature(signature, timestamp, nonce)) {
                    System.out.println("成功");
                    out.print(echostr);
                    out.flush();  //必须刷新
                }else {
                    System.out.println("失败");
                }
            } finally {
                out.close();
                out = null;

            }
        } else {// 进入POST聊天处理
            System.out.println("进入了聊天界面");
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
//            WxMaMessage msg = WxMaMessage.fromXml(request.getInputStream())

            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());

            /*BufferedReader readers = new BufferedReader(new InputStreamReader(request.getInputStream()));*/
            //JSONObject jsonObject = JSONObject.fromObject(responseStrBuilder.toString());
            String param= jsonObject.toString();
            System.out.println("转出来的数据:"+responseStrBuilder.toString());
            String kfliststr = selectKFList();
            System.out.println("在线客服列表："+kfliststr);
            JSONObject jobj = JSONObject.parseObject(kfliststr);
            System.out.println("在线客服列表2："+jobj.toString());
            JSONArray jsonArray = jobj.getJSONArray("kf_online_list");
            List<Map> list = JSONArray.parseArray(kfliststr, Map.class);
            if(jsonArray!=null && jsonArray.size()>0) {
                System.out.println("选择客服：" + jsonArray.get(0).toString());
                Map<String,Map<String,String>> map = new HashMap<>();
                //zw6352@gh_634acb1734ed
                Map<String,String> mapkf = new HashMap<>();
                mapkf.put("KfAccount","zw6352@gh_634acb1734ed");
                map.put("TransInfo",mapkf);
                jsonObject.put("TransInfo",mapkf);
                jsonObject.put("MsgType","transfer_customer_service");
                String tousername = jsonObject.getString("ToUserName");
                String fromusername = jsonObject.getString("FromUserName");
                jsonObject.put("ToUserName",fromusername);
                jsonObject.put("FromUserName",tousername);

                System.out.println("转发的消息指定客服："+jsonObject.toString());
                out.print(jsonObject.toString());
                out.flush();
            }
        }
        return null;
    }


//    @RequestMapping(value = {"/getProcessRequest"}, method = {RequestMethod.GET, RequestMethod.POST})
    public Object getProcessRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        System.out.println("方法是-------" + isGet);
        PrintWriter out = null;
        out = response.getWriter();
        if (isGet) {//首次验证token
            // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            try {
                // out = response.getWriter();
                // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
                if (checkSignature(signature, timestamp, nonce)) {
                    System.out.println("成功");
                    out.print(echostr);
                    out.flush();  //必须刷新
                }else {
                    System.out.println("失败");
                }
            } finally {
                out.close();
                out = null;

            }
        } else {// 进入POST聊天处理
            System.out.println("进入了聊天界面");
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            System.out.println("接受到的消息："+responseStrBuilder.toString());
            String kflist = selectKFList();
            System.out.println("客服列表："+kflist);

//            String sessionlist = getSessionList();
//            System.out.println("会话列表："+sessionlist);

            WxMaMessage msg = WxMaMessage.fromXml(responseStrBuilder.toString());
            //WxMaXmlOutMessage outMessage = new WxMaXmlOutMessage();
            WxMpXmlOutTransferKefuMessage outMessage = new WxMpXmlOutTransferKefuMessage();
            outMessage.setCreateTime(msg.getCreateTime().longValue());
            outMessage.setFromUserName(msg.getToUser());
            outMessage.setToUserName(msg.getFromUser());
            outMessage.setMsgType("transfer_customer_service");
            WxMpXmlOutTransferKefuMessage.TransInfo transInfo = new WxMpXmlOutTransferKefuMessage.TransInfo();
            transInfo.setKfAccount("zw6352@gh_634acb1734ed");
            outMessage.setTransInfo(transInfo);
//            WxMaKefuMessage wxMaKefuMessage = new WxMaKefuMessage();

            System.out.println("转发信息："+outMessage.toXml());
            out.write(outMessage.toXml());
            out.flush();
        }
        return null;
    }
    /**
     * 获取在线的客服列表
     * @return
     */
    private String selectKFList(){

        RestTemplate restTemplate = new RestTemplate ();
        String url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + wxrssService.getAccessToken ();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity (url, String.class);
        return responseEntity.getBody ();
    }

//    private String getSessionList(){
//        RestTemplate restTemplate = new RestTemplate();
//        String url = "https://api.weixin.qq.com/customservice/kfsession/create?access_token="+wxrssService.getAccessToken();
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
//        return responseEntity.getBody();
//    }

    /**
     * 验证签名
     * @param signature  验证签名的数据
     * @param timestamp  参数
     * @param nonce  参数
     * @return  boolean
     */
    public boolean checkSignature(String signature, String timestamp, String nonce) {
        //TOKEN
        //与token 比较
        String[] arr = new String[] {"cdytcxznkjyxgs", timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        content = null;
        // 将sha1加密后的字符串可与signature对比
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return  String
     */
    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return  String
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }
}
